<template>
  <div class="container">
    <ul class="list-unstyled">
      <li v-for="item of names" :key="item.url">
        <a :href="item.url" target="_blank">{{ item.name }}</a>
      </li>
    </ul>

    <div class="mt-3">
      <span>下载文件名：</span>
      <el-input placeholder="请输入文件名" v-model="dowaloadName" style="width: 300px">
        <template slot="append">.zip</template>
      </el-input>
      <el-button class="ml-3" type="primary" :loading="downloadLoading" @click="download">
        批量下载
      </el-button>
    </div>
  </div>
</template>

<script>
import { stringFileName, loadRemote, config, fileSaveAs } from '@vimi/utils-tool'
import { service } from '@vimi/utils-api'

const pizzipCdn = `${config.baseUrl}/libs/pizzip/3.0.6/pizzip.min.js`

export default {
  components: {},
  props: {},
  data() {
    return {
      urls: [
        'https://vimi8-dev.oss-cn-shenzhen.aliyuncs.com/app/bank/20212080902020507-lotxptq5.jpg',
        'https://vimi8-dev.oss-cn-shenzhen.aliyuncs.com/app/bank/20212080901058576-p3v5rfsg.jpg',
        'https://vimi8-dev.oss-cn-shenzhen.aliyuncs.com/credit/notice/Scan.pdf',
        'https://vimi8-dev.oss-cn-shenzhen.aliyuncs.com/video/7125ce9b-4397-4b01-a35b-776ead2061d0.mp4',
      ],
      names: [],
      dowaloadName: 'download',
      downloadLoading: false,
    }
  },
  computed: {},
  watch: {},
  created() {
    Promise.all([loadRemote(pizzipCdn, 'PizZip')]).then(() => {
      this.init()
    })
  },
  mounted() {},
  methods: {
    init() {
      this.names = this.urls.map(url => ({
        url,
        name: stringFileName(url),
      }))
    },

    async download() {
      try {
        this.downloadLoading = true

        const promises = this.urls.map(url => this.fetchData(url))
        const blobs = await Promise.all(promises)

        const zip = new window.PizZip()
        blobs.forEach((blob, index) => {
          const { name } = this.names[index]
          zip.file(name, blob)
        })

        // add folder
        zip
          .folder('vimi8')
          .file(
            '下载说明.txt',
            `下载内容来源于：${config.baseUrl} \n内容的所有信息数据以及观点、投资建议、投资分析等资料仅供参考，您据此操作而造成必然或偶然的损失，我公司和我们的信息服务提供商概不负责。`
          )

        const content = zip.generate({ type: 'blob' })
        fileSaveAs(content, `${this.dowaloadName || 'download'}.zip`)
      } catch (error) {
        this.$message.error('下载失败')
        throw new Error(error)
      } finally {
        this.downloadLoading = false
      }
    },

    async fetchData(url) {
      const res = await service.get(url, {
        responseType: 'arraybuffer',
      })
      return res.data
    },
  },
}
</script>

<style lang="scss" scoped></style>
